<?php

namespace plugin\admin\app\controller\auth;

use plugin\admin\app\common\xbuilder\XBuilderForm;
use plugin\admin\app\common\xbuilder\XBuilderList;
use plugin\admin\app\controller\Base;
use plugin\admin\app\controller\common\Crud;
use plugin\admin\app\model\AdminRoleThink;
use plugin\admin\app\model\AdminThink as ModelAdmin;
use plugin\admin\app\Util;

/**
 * 管理员设置
 */
class Admin extends Base
{

    /**
     * @var Admin
     */
    protected $model = null;

    /**
     * 增删改查
     */
    use Crud;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new ModelAdmin;
    }

    /**
     * 获取列表数据
     */
    public function index(){
        $sexOpt = [
            'type'=>'mapping',
            'map'=>[
                1=>'男',
                2=>'女',
                0=>'未知'
            ]
        ];
        $builder = new XBuilderList();
        return $builder->setMetaTitle(' ') // 设置页面标题
        ->addTopButton('add',$this->add())
            ->addTopButton('forbid')
            ->addTopButton('recycle')
            ->addTopButton('restore')
            ->addTopButton('delete')
            ->addTableColumn('id', 'ID','',false,true)
            ->addTableColumn('username', '用户名')
            ->addTableColumn('nickname', '昵称')
            ->addTableColumn('sex', '性别',$sexOpt)
            ->addTableColumn('avatar', '头像','image')
            ->addTableColumn('email', '邮箱')
            ->addTableColumn('mobile', '手机号码')
            ->addTableColumn('status', '状态', 'status')
            ->addTableColumn('created_at', '创建时间', 'datetime')
            ->addRightButton('edit',$this->edit()) // 添加编辑弹窗按钮
            ->addRightButton('forbid') // 添加编辑按钮
            ->addRightButton('resume') // 添加编辑按钮
            ->addRightButton('recycle') // 添加编辑按钮
            ->addRightButton('restore') // 添加编辑按钮
            ->addRightButton($this->delet()) // 添加编辑按钮
            ->setTableApi('/app/admin/auth/admin/list')
            ->getPageData();
    }
    public function list(){
        $orderBy = request()->input('orderBy', 'updated_at', 'string') ?: 'updated_at';
        $orderDir = request()->input('orderDir', 'desc', 'string') ?: 'desc';
        $orderArr = [
            'id' => 'desc',
            $orderBy => $orderDir
        ];
        $map[] = ['status','>','-1'];

        $data = $this->model
            ->with(['roles'])
            ->where($map)
            ->order($orderArr)
            ->withoutField(['password'])
            ->paginate();
        foreach ($data as $admin) {
            $roles = [];
            foreach ($admin['roles'] as $role) {
                if (!$role) {
                    continue;
                }
                $roles[] = $role['id'];
            }
            $admin['roles'] = implode(',', $roles);
        }
        $get_table_data = XBuilderList::handleTableData($data);
        return $this->resSucess('请求成功',$get_table_data);
    }
    public function delet()
    {
        if (request()->method() == 'POST') {
            $data = request()->post();
            $admin = ModelAdmin::find($data['id']);
            $admin->transaction(function ()  use ($admin,$data) {
                $admin->roles()->detach();
                $admin->delete();
            });
            return $this->json(0,'操作成功');
        } else {
            return [
                'type'=>'button',
                'label'=>'删除',
                'visibleOn'=>"true",
                'confirmText'=>'确定要删除?',
                'url'=>'/app/admin/auth/admin/delet',
            ];
        }
    }
    public function add()
    {
        return $this->form('add');
    }
    public function edit()
    {
        return $this->form('edit');
    }
    protected function form($type = 'add')
    {
        if (request()->method() == 'POST') {
            $model = $this->model;
            $data  = request()->except(['create_at']);
            if(isset($data['password']) && $data['password'])
            {
                $data['password'] = Util::passwordHash($data['password']);
            }
            // 更新admin表
            $model->startTrans();
            try{
                if($type === 'add'){
                    $result=$model->save($data);
                } else {
                    $result=$model->update($data);
                }
                $gather = $model->isEmpty() ? $result : $model;
                // 更新权限access中间表
                $roles = request()->post('roles');
                $access = explode(',',$roles);
                $gather->roles()->detach();
                $accessResult = $gather->roles()->save($access);
                if (!$result || !$accessResult) {
                    return $this->resError('操作失败');
                }
                $model->commit();
                return $this->resSucess('操作成功');
            }catch (\Throwable $exception){
                $model->rollback();
            }
        } else {
            // 使用FormBuilder快速建立表单页面
            $AdminRoleThink = new AdminRoleThink;
            $rolesSelect = $AdminRoleThink->getRoleFormatSelect();
            $statusOpt = [  //单选
                'type'=>'select',
                'options'=>[
                    ['label'=>'未审核', 'value'=>'0'], ['label'=>'驳回', 'value'=>'-1'], ['label'=>'审核', 'value'=>'1']
                ]
            ];
            $sexOpt = [  //单选
                'type'=>'select',
                'options'=>[
                    ['label'=>'男', 'value'=>'1'], ['label'=>'女', 'value'=>'2'], ['label'=>'未知', 'value'=>'*']
                ]
            ];
            $emailRule = [
                'required'=>true,
                'rule'=>[
                    'isEmail'=>true
                ],
                'errMsg'=>[
                    'isNumeric'=>'邮箱格式错误',
                ]
            ];
            $telRule = [
                'required'=>true,
                'rule'=>[
                    'matchRegexp'=>'/^[1][3,4,5,7,8,9][0-9]{9}$/'
                ],
                'errMsg'=>[
                    'matchRegexp'=>'请输入正确的手机号码',
                ]
            ];
            $builder = new XBuilderForm();
            return $builder->setMetaTitle('编辑管理员信息')
                ->setFormUrl($type)
                ->setFormMode('horizontal')
                ->addFormItem('username', 'text', '用户名', true)
                ->addFormItem('nickname', 'text', '昵称',true)
                ->addFormItem('sex', $sexOpt, '性别')
                ->addFormItem('password', 'password', '密码')
                ->addFormItem('avatar', 'image','头像')
                ->addFormItem('email', 'text','邮箱',$emailRule)
                ->addFormItem('mobile', 'text','手机号码',$telRule)
                ->addFormItem('roles', $rolesSelect,'角色选择')
                ->addFormItem('status', $statusOpt,'状态')
                ->setFooterAffix()
                ->getFormData();
        }
    }
}
